package common.config;

import cn.edu.hfut.dmic.webcollector.model.CrawlDatum;
import cn.edu.hfut.dmic.webcollector.net.HttpRequest;
import cn.edu.hfut.dmic.webcollector.net.HttpResponse;
import cn.edu.hfut.dmic.webcollector.net.Requester;

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;


/**
 * Created by wanglei on 2017/8/3.
 */
public class AbuyunDynamicProxyRequester implements Requester {
    /**
     *
     * @param proxyUser 阿布云动态代理用户名
     * @param proxyPass 阿布云动态代理密码
     */
    public AbuyunDynamicProxyRequester(String proxyUser, String proxyPass) {
        Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));
    }

    public HttpResponse getResponse(CrawlDatum crawlDatum) throws Exception {
        HttpRequest request = new HttpRequest(crawlDatum.url());
        String proxyServer = "http-dyn.abuyun.com";
        int proxyPort = 9020;
        InetSocketAddress addr = new InetSocketAddress(proxyServer, proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        request.setProxy(proxy);
        System.out.println("----------------------------------------");
        return request.response();
    }


    public static class ProxyAuthenticator extends Authenticator {
        private String user, password;

        public ProxyAuthenticator(String user, String password) {
            this.user = user;
            this.password = password;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }
    }
}
